package com.example.a_java.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
// 注释掉方法级安全注解的导入
// import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

/**
 * Spring Security配置类
 * 
 * 临时禁用方法级权限检查(@PreAuthorize)作为紧急解决方案
 * TODO: 在数据库初始化完成后，需要恢复方法级权限检查
 */
@Configuration
@EnableWebSecurity
// 注释掉方法级安全注解 - 这会使@PreAuthorize注解失效
// @EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置Security
     * 
     * 当前配置：所有已认证用户均可访问所有接口，不进行权限检查
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 允许跨域
            .cors()
            .and()
            // 禁用CSRF
            .csrf().disable()
            // 禁用Session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置请求授权
            .authorizeRequests()
                // 允许预检请求
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                // 允许所有人访问登录注册接口
                .antMatchers("/auth/login", "/auth/register").permitAll()
                // 允许所有人访问Swagger相关资源
                .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                // 允许所有人访问静态资源
                .antMatchers("/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
                // 其他所有请求只需要认证，不做权限判断
                .anyRequest().authenticated()
            .and()
            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }
    
    /**
     * 创建JwtAuthenticationFilter Bean
     */
    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilterBean() {
        return new JwtAuthenticationFilter();
    }
} 